package com.example.springai.controller;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpMessageHandler;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;

import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicReference;

@Slf4j
@Component
public class WeChatMessageHandler implements WxMpMessageHandler {

    @Autowired
    private ChatClient chatClient;

    @Autowired
    private WxMpService wxMpService;

    @Autowired
    private Executor asyncExecutor; // 线程池用于异步处理


    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService, WxSessionManager sessionManager) {
        String userOpenId = wxMessage.getFromUser(); // 用户 OpenID
        String inputText = wxMessage.getContent();  // 用户输入内容

        log.info("收到用户消息: {}", inputText);
        // 自动回复文本消息
        String reply = "";
//        reply = chatClient.prompt()
//                .user("java是什么？回答请在100字以内。")
//                .call()
//                .content();

        log.info("reply: {}", reply);

        reply = "AI 正在 思考...";
        // 第一步：返回正常回复消息
        WxMpXmlOutMessage responseMessage = WxMpXmlOutMessage.TEXT()
                .content(reply)
                .fromUser(wxMessage.getToUser())
                .toUser(userOpenId)
                .build();

        // 第二步：异步主动推送另一条消息
        asyncExecutor.execute(() -> sendAdditionalMessage(userOpenId,inputText));

        return responseMessage;

    }

    private void sendAdditionalMessage(String openId, String inputText) {
        String additionalMsg = chatClient.prompt()
                .user(inputText + "|回答请在100字以内。")
                .call()
                .content();

        try {
            WxMpKefuMessage kefuMessage = WxMpKefuMessage.TEXT()
                    .toUser(openId)
                    .content(additionalMsg)
                    .build();

            this.wxMpService.getKefuService().sendKefuMessage(kefuMessage);
            log.info("已向用户 {} 主动推送消息", openId);
        } catch (Exception e) {
            log.error("主动推送消息失败", e);
        }
    }


}
